# -*- coding: utf-8 -*-
"""
Created on Wed Jun 28 15:04:37 2017

@author: qiang.qian
"""
import json
import requests
import datetime
import sys
import csv

stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")

path = 'D:\\QIAN\\CODE\\oschina\\userprofile\\cloud\\'
file = '8'
sources_file = path + 'mails_' + file + '.txt'
result_file = open(path + 'result_' + file + '_' + stamp + ".txt", "w")

def desmail(info):
    url = 'http://coreinfo.arc.ctripcorp.com/decryptservice/api/decrypt'
    headers = {'content-type': 'application/json'}
    values = {
            "appId":"100009072",
            "op":"qiang.qian"
    }
    
    value = {}
    value['key'] = info[1]
    value['type'] = 2
    values['info'] = value
  
    try:
        data = json.dumps(values)

        res = requests.post(url=url,data=data,headers=headers)
        j = json.loads(res.text)
        
        mail = j['result']['2']['data']
        return mail
    except Exception as e:
        print("Unexpected error:", sys.exc_info()[0])
        print(info)
        print(value)
        return {}

def savemail(mail):
    try:
        for (k,v) in  mail.items():
            result_file.write("{0}\t{1}\n".format(k,v))
    except Exception as e:
        print("Unexpected error:", sys.exc_info()[0])
        print(mail)
# main

with open(sources_file, 'r',encoding='utf8') as f:
    reader = csv.reader(f,delimiter='\t')
    lines = list(reader)
try:
    i = 0
    for info in lines:
        mail=desmail(info)
        savemail(mail)
        i = i + 1
        print(i)
        if(i % 5000 == 0):
             result_file.flush()

    print("done")
except KeyboardInterrupt:
    print("break")
    sys.exit()
finally:
    result_file.flush()
    result_file.close()

    